<script setup lang="ts">
import { reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { loginApi } from '@/api/login'
import router from '@/router'
import { useInfoStore } from '@/stores/info'

const infoStore = useInfoStore()
const ruleFormRef = ref<FormInstance>()

const validateAccount = (rule: any, value: any, callback: any) => {
    if (value === '') {
        callback(new Error('请输入账号'))
    } else {
        callback()
    }
}
const validatePassword = (rule: any, value: any, callback: any) => {
    if (value === '') {
        callback(new Error('请输入密码'))
    } else {
        callback()
    }
}

const ruleForm = reactive({
    account: '',
    password: ''
})

const rules = reactive<FormRules<typeof ruleForm>>({
    account: [{ validator: validateAccount, trigger: 'blur' }],
    password: [{ validator: validatePassword, trigger: 'blur' }],
})


// 登录
const handleLogin = async () => {
    if (!ruleFormRef.value) return
    await ruleFormRef.value.validate()
    const params = {
        email: ruleForm.account,
        password: ruleForm.password
    }
    const {data} = await loginApi(params)
    
    localStorage.setItem('token', data.token)
    infoStore.info.token = data.token
    infoStore.info.userInfo = data.userInfo

    ruleFormRef.value.resetFields()
    router.push({ name: 'home' })
}
</script>

<template>
    <div class="login">
        <div class="login-container">
            <el-form ref="ruleFormRef" :model="ruleForm" status-icon :rules="rules" label-width="40px">
                <el-form-item label="账号" prop="account">
                    <el-input  style="width: 320px;" placeholder="请输入账号" v-model="ruleForm.account" type="text" autocomplete="off" />
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input  style="width: 320px;" placeholder="请输入密码" v-model="ruleForm.password" type="password" autocomplete="off" />
                </el-form-item>

                <el-form-item>
                    <el-button @click="handleLogin" style="width: 100%;" type="primary">登 录</el-button>
                </el-form-item>
            </el-form>  
        </div>
    </div>
</template>

<style scoped lang="scss">
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-image: url("../assets/images/login-background.jpeg");
  background-size: cover;

  &-container {
    padding: 20px;
    background-color: rgba(255, 255, 255, 0.2);
    margin-top: -40px;
  }
}
</style>